package com.example.demo;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Set;
import java.util.TreeMap;

public class RedisDemoGeneric {
    public static void test(Jedis jedis) {
        System.out.println("set 和 get 使用");
        //清空数据库
        jedis.flushAll();
        jedis.set("key","k1");
        jedis.set("key2","k2");
        jedis.set("key3","k3");
        String key = jedis.get("key");
        String key2 = jedis.get("key2");
        String key3 = jedis.get("key3");
        System.out.println("key: " + key);
        System.out.println("key2: " + key2);
        System.out.println("key3: " + key3);

        System.out.println("exists 和 del 使用");
        boolean result = jedis.exists("key");
        System.out.println("result:" + result);
        result = jedis.exists("key1111");
        System.out.println("result:" + result);

        long del = jedis.del("key", "key2");
        result = jedis.exists("key");
        System.out.println("result:" + result);

        System.out.println("keys 使用");
        jedis.set("key","k1");
        jedis.set("key2","k2");
        Set<String> keys = jedis.keys("*");
        System.out.println("keys: " + keys);

        System.out.println("expire 和 ttl 使用");

        jedis.set("key4","k4");
        jedis.expire("key4",10);
        //休眠5s
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        long ttl = jedis.ttl("key4");
        System.out.println("ttl: " + ttl );

        System.out.println("type 使用");
        jedis.flushAll();
        jedis.set("String", "1");
        String type = jedis.type("String");
        System.out.println("type: "+type);

        jedis.lpush("list","111","222","333");
        type = jedis.type("list");
        System.out.println("type: "+type);

        jedis.sadd("set","a","b","c");
        type = jedis.type("set");
        System.out.println("type: "+type);

        jedis.zadd("zset",1.0,"zhangsan");
        type = jedis.type("zset");
        System.out.println("type: "+type);

        jedis.hset("hash","f1 ","v1");
        type = jedis.type("hash");
        System.out.println("type: "+type);

    }

    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:8888");
        try(Jedis jedis = jedisPool.getResource()) {
            test(jedis);
        }
    }
}
